class Store {
  constructor (keyName, defaultValue) {
    this.keyName = keyName
    this.defaultValue = defaultValue
    this.loadFromLocalStorage()
    // console.log(keyName + 'constructed')
  }

  loadFromLocalStorage () {
    if (!localStorage.getItem(this.keyName)) {
      localStorage.setItem(this.keyName, JSON.stringify(this.defaultValue))
    }
    try {
      this.state = JSON.parse(localStorage.getItem(this.keyName))
    } catch (e) {
      localStorage.setItem(this.keyName, JSON.stringify(this.defaultValue))
      // debugger
    } finally {
      this.state = JSON.parse(localStorage.getItem(this.keyName))
    }
  }

  append (item) {
    this.state.push(item)
    this._commit()
  }

  remove (item) {
    this.state = this.state.filter((i) => i !== item)
    this._commit()
  }

  removeById (id) {
    this.state = this.state.filter((i) => i.uuid !== id)
    this._commit()
  }

  findById (id) {
    return this.state.filter(i => i.uuid === id).pop()
  }

  _commit () {
    localStorage.setItem(this.keyName, JSON.stringify(this.state))
  }

  toString () {
    var that = this
    console.log(that.state)
  }

  iterate (callback) {
    this.state.filter(callback)
  }

  update (state) {
    this.state = state.filter(i => i)
    this._commit()
  }
}

export const store = new Store('commands', [])

export const settingsStore = new Store('settings',
  [{
    optionName: 'theme',
    options: [
      { name: 'dark', status: false },
      { name: 'light', status: true }]
  }])
